import 'dart:ffi';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_ohos/app/common/fold_status_provider.dart';
import 'package:flutter_ohos/app/common/global.dart';
import 'package:flutter_ohos/app/common/widgets/toast.dart';
import 'package:flutter_ohos/app/modules/fourth/component/setting_detail.dart';
import 'package:flutter_ohos/app/modules/fourth/fourth_view.dart';
import 'package:flutter_ohos/app/utils/log_utils.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import 'mine_provider.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:lottie/lottie.dart';
import 'package:permission_handler/permission_handler.dart';

class MinePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => MineProvider()..initData(),
      builder: (context, child) => _buildPage(context),
    );
  }

  Widget _buildPage(BuildContext context) {
    final provider = context.read<MineProvider>();
    final state = provider.state;

    final statusProvider = context.read<FoldStatusProvider>();

    return Consumer<FoldStatusProvider>(builder: (context, sProvider, child) {
      LogUtils.d(
          "sProvider.foldStatus=${sProvider.foldStatus}, Global.screenWidth= ${sProvider.screenWidth}, Media.screenEidth= ${MediaQueryData.fromWindow(window).size.width}");

      if (sProvider.foldStatus == FoldStatus.expanded) {
        return Row(
          children: [
            Container(
              width: sProvider.screenWidth/2,
              child: Scaffold(
                  backgroundColor: Colors.lightBlue,
                  body: ListView(children: [
                    buildPersonalInfoView(context),
                    buildSettingView(context),
                    buildTipView(context)
                  ])),
            ),
            Consumer<MineProvider>(builder: (context, provider, child) {
              return Expanded(child: Container(
                  child: SettingDetail(
                    title: state.curTitle,
                  )));
            })
          ],
        );
      } else {
        return Scaffold(
            backgroundColor: Colors.lightBlue,
            body: ListView(children: [
              buildPersonalInfoView(context),
              buildSettingView(context),
              buildTipView(context)
            ]));
      }
    });
  }
}

///配置信息
Widget buildSettingView(BuildContext context) {
  return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: 20),
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Consumer<MineProvider>(builder: (context, provider, child) {
        return ListView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: provider.state.serviceList.length,
          itemBuilder: (context, i) {
            return _buildItem(context, provider.state.serviceList.elementAt(i));
          },
        );
      }));
}

Widget _buildItem(BuildContext context, Map item) {
  final provider = context.read<MineProvider>();
  final statusProvider = context.read<FoldStatusProvider>();

  return GestureDetector(
    onTap: () {
      if (statusProvider.foldStatus == FoldStatus.expanded) {
        provider.changeTitle(item["content"]);
      } else {
        provider.jumpToFourthPage(item["content"]);
      }
    },
    child: Container(
      height: 50,
      child: Column(
        children: [
          Row(
            children: [
              // Icon(),

              Expanded(child: Text(item["content"]))
            ],
          ),
          Divider(),
        ],
      ),
    ),
  );
}

///顶部个人信息
Widget buildPersonalInfoView(BuildContext context) {
  return Container(
      margin: EdgeInsets.only(left: 10, right: 10, top: Global.paddingTop + 40),
      padding: EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Consumer<MineProvider>(builder: (context, provider, child) {
        return Column(
          children: [
            Row(
              children: [
                ///头像
                SizedBox(
                  width: 60,
                  height: 60,
                  child: CircleAvatar(
                    backgroundColor: Colors.transparent,
                    child: Image.asset("assets/images/head_img.png"),
                    // backgroundImage: NetworkImage(
                    //     'https://img0.baidu.com/it/u=645606765,1278668075&fm=253&fmt=auto&app=120&f=JPEG?w=200&h=200'),
                  ),
                ),

                ///个人信息
                Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        provider.state.userData.name ?? '',
                        style: TextStyle(fontSize: 14),
                      ),
                      const SizedBox(
                        height: 8,
                      ),
                      Text(
                        "会员号：${provider.state.userData.account}",
                        style: TextStyle(fontSize: 14),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Container(
              alignment: Alignment.centerLeft,
              margin: EdgeInsets.only(top: 10),
              child: Row(
                children: [
                  const Expanded(
                      child: Text(
                    '您还不是会员',
                    style: TextStyle(fontSize: 12),
                  )),
                  const Icon(
                    CupertinoIcons.heart_fill,
                    color: Colors.pink,
                    size: 24.0,
                  ),
                  TextButton(
                    onPressed: () {
                      // provider.jumpToSixPage();
                      provider.jumpToSevenPage();
                    },
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.blue),
                      shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                          RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                        // side: BorderSide(color: Colors.red)
                      )),
                      padding: MaterialStateProperty.all(
                          const EdgeInsets.symmetric(horizontal: 12)),
                    ),
                    child: const Text(
                      '会员中心',
                      style: TextStyle(color: Colors.white),
                    ),
                  )
                ],
              ),
            ),

            TextButton(
              child: Text("DateTimePicker In Page"),
              onPressed: () {
                // Navigator.of(context)
                //     .push(MaterialPageRoute(builder: (context) {
                //   return DateTimePickerWidget();
                // }));
                Get.bottomSheet(
                    SizedBox(
                        width: double.infinity,
                        height: 260,
                        child: DateTimePickerWidget()
                    )
                );
              },
            ),
            
            TextButton(onPressed: () async {
              final dio = Dio();
              final cookieJar = CookieJar();
              dio.interceptors.add(CookieManager(cookieJar));
              await dio.get('https://baidu.com/');
              // Print cookies
              print('*********cookies*******');
              var tmpCookie = await cookieJar.loadForRequest(Uri.parse('https://baidu.com/'));
              print(tmpCookie);
              showToast(tmpCookie.toString());
              // second request with the cookie
              await dio.get('https://baidu.com/');
            }, child:  Text("测试dio_cookie_manager")),

            Lottie.asset('assets/images/service.json'),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(
                  child: Text("show loading"),
                  onPressed: () {
                    EasyLoading.showToast('Toast');
                  },
                ),
                TextButton(
                  child: Text("dismiss loading"),
                  onPressed: () {
                    EasyLoading.dismiss();
                  },
                ),
              ],
            ),

            /// 权限申请测试，测试结果：支持相册、定位，不支持获取OAID APP_TRACKING_CONSENT权限
            TextButton(onPressed: () async {
              permissionApply();
            }, child:  Text("权限申请测试"))
          ],
        );
      }));
}

Future<void> permissionApply() async {
  var status = await Permission.appTrackingTransparency.status;
  if (status == PermissionStatus.denied) {
    await Permission.appTrackingTransparency.request();
  }
}

///提示信息
Widget buildTipView(BuildContext context) {
  return Container(
    margin: const EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 30),
    child: const Text(
      "特别声明：此APP中的个人数据默认全部保存在手机本地，此APP中的个人数据默认全部保存在手机本地此APP中的个人数据默认全部保存在手机本地此APP中的个人数据默认全部保存在手机本地此APP中的个人数据默认全部保存在手机本地此APP。",
      style: TextStyle(color: Colors.white, fontSize: 12),
    ),
  );
}
